""" 
旋转编码器
说明:
    https://www.yiboard.com/thread-1788-1-1.html
    
工作原理:
    sw
        0: 按下
        1: 未按下
    clk = output_a 下降沿时:
        dt = output_b = 1: 顺时针
        dt = output_b = 0: 逆时针
    clk = output_a 上升沿时:
        dt = output_b = 1: 逆时针
        dt = output_b = 0: 顺时针

接线:
    clk_roa -> 32
    dt_rob -> 25
    sw_pin -> 26

"""

from machine import Pin, ADC
import time

Roa_Pin_Num = 32  # 旋转编码器clk
Rob_Pin_Num = 25  # 旋转编码器dt
Sw_Pin_Num = 26  # 旋转编码器sw
roa = None
rob = None
sw_pin = None
count = 0


def irq_sw_pin(pin):
    global count
    count = 0  # 计数器清空


def init_setup():
    global Roa_Pin_Num, Rob_Pin_Num, Sw_Pin_Num
    global roa, rob, sw_pin

    roa = Pin(Roa_Pin_Num, Pin.IN)
    rob = Pin(Rob_Pin_Num, Pin.IN)
    sw_pin = Pin(Sw_Pin_Num, Pin.IN, Pin.PULL_UP)
    sw_pin.irq(trigger=Pin.IRQ_FALLING, handler=irq_sw_pin)


def cal_rotary():
    global count
    global roa, rob

    cur_roa_state = roa.value()
    while cur_roa_state == roa.value():
        # 等待roa变化: 触发上升沿或下降沿
        time.sleep_ms(2)

    cur_rob_state = rob.value()
    if cur_roa_state == 0:
        """上升沿"""
        if cur_rob_state == 0:
            count += 1
        else:
            count -= 1
    else:
        """下降沿"""
        if cur_rob_state == 1:
            count += 1
        else:
            count -= 1


def loop_run():
    global count
    last_count = 0
    while True:
        cal_rotary()
        if last_count != count:
            print(f"count: {count}")
            last_count = count


if __name__ == "__main__":
    init_setup()
    loop_run()
